package com.changan.util;


import com.changan.entity.Menu;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MenuTreeBuilder {

    public static List<Menu> build(List<Menu> menuList){

        //定义一个最后的结果
        List<Menu> menus=new ArrayList<Menu>();
        //如果菜单里面的parentId=0.则是一级菜单
        for (int i=0;i<menuList.size();i++){
            //说明这个菜单为以及菜单
            if (menuList.get(i).getParentId()==0){
                menus.add(menuList.get(i)); //设置了父级的菜单
            }
        }

        for (Menu menu:menus){
            menu.setChildMenus(getChild(menu.getId(),menuList));
        }
        Collections.sort(menus,Menu.order());

        return menus;

    }
    private static List<Menu> getChild(Long id,List<Menu> menuList) {
        List<Menu> childList = new ArrayList<>();
        for (Menu menu : menuList) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (menu.getParentId().equals(id)) {
                childList.add(menu);
            }

        }
        Collections.sort(childList,Menu.order());
        // 把子菜单的子菜单再循环一遍
        for (Menu menu : childList) {// 没有url子菜单还有子菜单
            // 递归
            menu.setChildMenus(getChild(menu.getId(), menuList));
        }
        if (childList.size()==0){
            return null;
        }

        return childList;

    }
}
